{extend name="../../admin/view/main"}

{block name='content'}
<form  id="DataForm" autocomplete="off" class="layui-form layui-card">
    <div class="layui-card-body padding-40">

        <div class="layui-col-xs12 relative block">
            <span class="color-green font-w7 label-required-prev">来源城市</span>
            <span class="color-desc margin-left-5">（原区域：{$vo.from_province|default='--'} - {$vo.from_city|default=''}）</span>
            <div class="layui-row layui-col-space10">
                <label class="layui-col-xs4"><select class="layui-select from_province" lay-filter="from_province" name="from_province"></select></label>
                <label class="layui-col-xs4"><select class="layui-select from_city" lay-filter="from_city" name="from_city"></select></label>
            </div>
        </div>

        <div class="layui-col-xs12 relative block">
            <span class="color-green font-w7 label-required-prev">归属城市</span>
            <span class="color-desc margin-left-5">（原区域：{$vo.to_province|default='--'} - {$vo.to_city|default=''} ）</span>
            <div class="layui-row layui-col-space10">
                <label class="layui-col-xs4"><select class="layui-select" lay-filter="to_province" name="to_province"></select></label>
                <label class="layui-col-xs4"><select class="layui-select"  lay-filter="to_city" name="to_city"></select></label>
            </div>
        </div>

<!--        <div class="goods-item-box">-->
<!--            <div class="layui-clear">-->
<!--                <fieldset>-->
<!--                    <legend><span class="layui-badge think-bg-violet">状态</span></legend>-->
<!--                    <div class="layui-form-item">-->
<!--                        {foreach [1 => '启用',0 => '禁用'] as $k=>$v}-->
<!--                        {if (isset($vo.status) and $vo.status eq $k) or (empty($vo.status) and $k eq 1)}-->
<!--                        <input checked name="status" title="{$v}" type="radio" value="{$k}">-->
<!--                        {else}-->
<!--                        <input name="status" title="{$v}" type="radio" value="{$k}">-->
<!--                        {/if}{/foreach}-->
<!--                    </div>-->
<!--                </fieldset>-->
<!--            </div>-->
<!--        </div>-->


        <div class="layui-col-xs12 relative block margin-top-10">
            <span class="color-green font-w7 label-required-prev margin-left-10">调度员</span>
            <br>
            <div class="layui-input-inline">
                <input class="layui-input inline-block" name="uuid_docking_name" placeholder="调度员" required style="width:240px" value="{$uuid_docking_name}">
            </div>
        </div>

        <div class="layui-col-xs12 relative block">
            <div class="layui-card-header text-center margin-20 font-w7 color-text layui-bg-gray border-radius-5">
                城市负责人配置
            </div>
            <div class="layui-card-body margin-top-20 padding-bottom-0">
                <div class="padding-left-20" data-rule-list>
                    <div class="layui-form-item text-center">
                        <a class="layui-btn layui-btn-primary" data-item-add>添加员工</a>
                    </div>
                </div>
                <div class="hr-line-dashed margin-top-30"></div>
            </div>
        </div>

        <div class="hr-line-dashed"></div>
        {notempty name='vo.id'}<input name='id' type='hidden' value='{$vo.id}'>{/notempty}

        <div class="layui-form-item text-center">
            <button class="layui-btn sb" type="submit">保存数据</button>
            <button class="layui-btn layui-btn-danger" data-confirm="确定要取消编辑吗？" data-history-back type='button'>取消编辑</button>
        </div>
    </div>

</form>

<div class="layui-hide" data-item-tpl>
    <div class="layui-form-item jy-box" data-rule-item>
        <label class="layui-input-inline nowrap relative margin-bottom-5" style="width:300px">
            <b class="notselect color-green margin-right-5">接单上限</b>
            <input class="layui-input inline-block" name="limits[]" placeholder="请输入接单上限" required style="width:240px" value="1" type="number" step="1" min="0">
        </label>
        <label class="layui-form-item relative block nowrap margin-bottom-5" style="width:300px">
            <b class="notselect color-green margin-right-5">占比比重</b>
            <input class="layui-input inline-block" name="percentages[]" placeholder="请输入占比比重" required style="width:240px" value="1" type="number" step="1" min="1">
            <a class="layui-btn layui-btn-primary" data-item-rm><i class="layui-icon layui-icon-close margin-0"></i></a>
        </label>
        <label class="layui-form-item relative block nowrap" style="width:300px">
            <b class="notselect color-green margin-right-5">员工</b>
            <input class="layui-input inline-block" name="uuids[]" placeholder="请选择员工" required style="width:240px" value="">
            <a class="layui-btn layui-btn-primary" data-prefix="" data-rule-page="{:url('admin/user/select?authorize=3')}">选择员工</a>
        </label>

        <label class="layui-form-item relative block nowrap" style="width:300px">
            <b class="notselect color-green margin-right-5">现有组人力<i class="layui-icon layui-icon-help small-icon" data-tips-text="现有组人力指是否统计入当前有效人力，不涉及人员派单"></i></b>
            <input style="width:240px" required checked name="group_power_status[]" title="开启" type="radio" value="1">
            <input style="width:240px" required name="group_power_status[]" title="关闭" type="radio" value="0">
        </label>

        <label class="layui-form-item relative block nowrap" style="width:300px">
            <b class="notselect color-green margin-right-5">是否前线运营<i class="layui-icon layui-icon-help small-icon" data-tips-text="是否为前线运营指的是直接对接运满满，若开启则是施工师傅直接对接运满满，若关闭则是施工对接真惠审，对接运满满将不进行派单，对接真惠审，由真惠审进行派单"></i></b>
            <input style="width:240px" required checked name="online_status[]" title="开启" type="radio" value="1">
            <input style="width:240px" required name="online_status[]" title="关闭" type="radio" value="0">
        </label>
    </div>
</div>

<label class="layui-hide">
    <textarea id="DefaultData">{$data|default=[]|json_encode}</textarea>
</label>


<style>
    [data-rule-page] {
        margin-top: -3px;
        margin-left: 5px;
    }

    [data-rule-item] {
        padding-left: 40px;
        margin-bottom: 20px;
    }

    [data-item-dn], [data-item-up], [data-item-rm] {
        margin-top: -4px;
        margin-left: 5px;
    }

     .small-icon {
         font-size: 12px; /* 调整图标的大小 */
         color: #0C0C0C;
     }
</style>

<script>
    /*! 表单初始化 */
    window.form.render();
    let newArr = []

    require(['pcasunzips'], function () {
        (function (prov, city, area, refresh) {
            new PCAS("from_province", "from_city", prov, city);
            refresh(), form.on('select(from_province)', refresh), form.on('select(from_city)', refresh), form.on('select(area)', refresh);
        })('{$vo.from_province|default=""}', '{$vo.from_city|default=""}', '', function (data) {
            (data && $(data.elem).trigger('change')), setTimeout(function () {
                layui.form.render();
            }, 100);
        });
    });

    require(['pcasunzips'], function () {
        (function (prov, city, area, refresh) {
            new PCAS("to_province", "to_city", prov, city);
            refresh(), form.on('select(to_province)', refresh), form.on('select(to_city)', refresh), form.on('select(area)', refresh);
        })('{$vo.to_province|default=""}', '{$vo.to_city|default=""}', '', function (data) {
            (data && $(data.elem).trigger('change')), setTimeout(function () {
                layui.form.render();
            }, 100);
        });
    });

    (function (data) {
        /*! 默认数据渲染 */
        if (data.length < 1) addItem();
        else data.forEach(function (item) {
            addItem(item)
        });
        /*! 数据选项操作 */
        $('[data-rule-list]').on('click', '[data-rule-page]', function ($that) {
            $that = $(this), top.setItemValue = function (value) {
                $that.prevAll('input').val(($that.data('prefix') + '{v}').replace('{v}', value));
            };
            $.form.iframe($(this).data('rule-page'), $that.data('title') || $that.text(), ['930px', '600px']);
        }).on('click', '.layui-form-radioed', function () {
            if(newArr.length === 0){
                getTrueValue()
            }
            let index = newArr.findIndex(item => item.name === $(this).siblings('input')[0].name)
            newArr[index].value = $(this).children('div').text() === '开启' ? 1 : 0
        }).on('click', '[data-item-add]', function () {
            addItem();
        }).on('click', '[data-item-rm]', function () {
            $(this).parents('[data-rule-item]').remove();
            $(this).parents('[data-rule-item]').find('input').remove();
        }).on('click', '[data-item-up]', function () {
            var item = $(this).parents('[data-rule-item]');
            var prev = item.prev('[data-rule-item]');
            if (item.index() > 0) item.insertBefore(prev);
        }).on('click', '[data-item-dn]', function () {
            var item = $(this).parents('[data-rule-item]');
            var next = item.next('[data-rule-item]');
            if (next) item.insertAfter(next);
        });
        /*! 表单提交处理 */
        $('form#DataForm').vali(function (ret) {
            var idx;

            ret.limits = [];
            $('[name^="limits"]').each(function () {
                var value = $(this).val();
                var $parentItem = $(this).closest('.jy-box');
                if (value && $parentItem.is(':visible')) {
                    ret.limits.push(value);
                }
            });

            ret.percentages = [];
            $('input[name^="percentages"]').each(function () {
                var value = $(this).val();
                var $parentItem = $(this).closest('.jy-box');
                if (value && $parentItem.is(':visible')) {
                    ret.percentages.push(value);
                }
            });

            ret.uuids = [];
            $('input[name^="uuids"]').each(function () {
                var value = $(this).val();
                var $parentItem = $(this).closest('.jy-box');
                if (value && $parentItem.is(':visible')) {
                    ret.uuids.push(value);
                }
            });

            for (idx in ret.percentages) {
                if (!ret.percentages[idx]) return $.msg.tips('请输入占比比重');
            }
            for (idx in ret.limits) {
                if (!ret.limits[idx]) return $.msg.tips('请输入接单上限');
            }

            newArr.forEach((item) =>{
                ret[item.name] = item.value
            })

            console.log(ret);

            $.ajax({
                type: "post",           //传输方式 get/post
                url: "{:request()->url()}",       //传输地址（后台地址）
                data: ret,                //传参 {'url': url}数组形式
                dataType: "json",                  //接收数据形式
                success: function (res) {
                    if(res.code !== 1){
                        layer.msg(res.info);
                        return
                    }
                    window.history.back();
                },
                fail: function (err){
                    console.log(err)
                }
            })
            // $.form.load('{$request->url()}', {data: JSON.stringify(data)}, 'post');
        });
    })(JSON.parse($('#DefaultData').val() || '[]') || []);

    /*! 添加数据选项 */
    function addItem(data) {
      var $tpl = $('[data-item-tpl]').clone().removeClass('layui-hide').removeAttr('data-item-tpl');
      var indexSuffix = '_' + Math.floor(Math.random() * 1000000);

      if (data) {
        $tpl.find('[name^="percentages"]').val(data.percentage);
        $tpl.find('[name^="limits"]').val(data.limit);
        $tpl.find('[name^="uuids"]').val(data.user.id + "#" + data.user.name);

        var $groupPowerStatus = $tpl.find('[name^="group_power_status"]');
        $groupPowerStatus.attr('name', 'group_power_status' + indexSuffix);
        var groupPowerStatusValue = data.group_power_status;
        $groupPowerStatus.filter('[value="' + groupPowerStatusValue + '"]').prop('checked', true);

        var $onlineStatus = $tpl.find('[name^="online_status"]');
        $onlineStatus.attr('name', 'online_status' + indexSuffix);
        var onlineStatusValue = data.online_status;
        $onlineStatus.filter('[value="' + onlineStatusValue + '"]').prop('checked', true);
      } else {
        $tpl.find('[name^="group_power_status"]').attr('name', 'group_power_status' + indexSuffix);
        newArr.push({name:  'group_power_status' + indexSuffix, value : 1})

        $tpl.find('[name^="online_status"]').attr('name', 'online_status' + indexSuffix);
        newArr.push({name:  'online_status' + indexSuffix, value : 1})
        console.log($tpl)
      }

      $('[data-item-add]').parent().before($tpl);

      setTimeout(function () {
        $.form.reInit();
        layui.form.render('radio');


      }, 100);
    }
    setTimeout(()=>{
        getTrueValue()
    },500)
    // 修改数据
    let getTrueValue = function (){
        let arr = $('.layui-form-item').children('.label-required-prev').find('input:radio')
        for(let i = 0; i< arr.length;i++){
            let inIndex = newArr.findIndex((item)=>item.name === arr[i].name)
            if(inIndex === -1 &&  arr[i].name !== 'group_power_status[]' &&  arr[i].name !== 'online_status[]'){
                newArr.push( {name: arr[i].name})
            }
            let index = newArr.findIndex((item)=>item.name === arr[i].name)
            if(index !== -1){
                if(arr[i].value === '1'){
                    newArr[index].value = arr[i].checked ? 1 : 0
                }
            }
        }
    }

    layui.use(['form'], function() {
        var form = layui.form;


        form.render();

        //  监听事件
        $('.from_city').on('change',function (){
            let province = $('.from_province').val()
            let city = $(this).val()
            $.ajax({
                url: "{:url('getDockingUuid')}", // 替换为实际的接口 URL
                type: 'GET',
                dataType: 'json',
                data: { from_province: province, from_city: city},
                success: function(response) {
                    if (response.code === 1) {
                        var dockingName = response.data.uuid_docking_name;
                        $('input[name="uuid_docking_name"]').val(dockingName);
                    } else {
                        console.log('请求失败');
                    }
                },
                error: function() {
                    console.log('请求错误');
                }
            });
        })

    });

</script>
{/block}